<template>
  <view class="content">
    <u-navbar title="产品分类" :border="false" :autoBack="true"></u-navbar>
    
    <!-- 搜索工具栏 -->
    <view class="toolbar">
      <u-search v-model="searchKey" placeholder="请输入分类名称" @search="search" @custom="search"></u-search>
      <u-button type="primary" text="新增分类" @click="openAddDialog"></u-button>
    </view>
    
    <!-- 分类树形结构 -->
    <view class="tree-container">
      <u-empty v-if="treeData.length === 0" text="暂无分类数据"></u-empty>
      <view v-else>
        <view v-for="(item, index) in treeData" :key="item.id" class="tree-item">
          <view class="tree-item-header" @click="toggleChildren(item)">
            <view class="tree-item-title">
              <u-icon :name="item.hasChildren && item.expanded ? 'arrow-down' : 'arrow-right'" size="24"></u-icon>
              <text>{{ item.name }}</text>
            </view>
            <view class="tree-item-actions">
              <u-button type="info" text="添加子分类" size="mini" @click.stop="openAddChildDialog(item)" :disabled="item.level >= 2"></u-button>
              <u-button type="primary" text="编辑" size="mini" @click.stop="openEditDialog(item)"></u-button>
              <u-button type="error" text="删除" size="mini" @click.stop="confirmDelete(item)"></u-button>
            </view>
          </view>
          
          <view class="tree-children" v-if="item.hasChildren && item.expanded">
            <view v-for="child in item.children" :key="child.id" class="tree-child-item">
              <view class="tree-child-title">
                <text>{{ child.name }}</text>
              </view>
              <view class="tree-item-actions">
                <u-button type="primary" text="编辑" size="mini" @click.stop="openEditDialog(child)"></u-button>
                <u-button type="error" text="删除" size="mini" @click.stop="confirmDelete(child)"></u-button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 分类表单弹窗 -->
    <u-popup v-model="showForm" mode="center" width="80%" height="auto">
      <view class="form-container">
        <view class="form-header">
          <text>{{ formTitle }}</text>
          <u-icon name="close" @click="showForm = false"></u-icon>
        </view>
        <view class="form-content">
          <u-form :model="formData" ref="uForm">
            <u-form-item label="分类名称" prop="name" :required="true">
              <u-input v-model="formData.name" placeholder="请输入分类名称"></u-input>
            </u-form-item>
            <u-form-item label="分类编码" prop="code">
              <u-input v-model="formData.code" placeholder="请输入分类编码"></u-input>
            </u-form-item>
            <u-form-item label="分类描述" prop="description">
              <u-input v-model="formData.description" type="textarea" placeholder="请输入分类描述"></u-input>
            </u-form-item>
            <u-form-item label="排序" prop="sort">
              <u-input v-model="formData.sort" type="number" placeholder="请输入排序"></u-input>
            </u-form-item>
          </u-form>
        </view>
        <view class="form-footer">
          <u-button type="info" text="取消" @click="showForm = false"></u-button>
          <u-button type="primary" text="确认" @click="submitForm"></u-button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      searchKey: '',
      treeData: [],
      showForm: false,
      formTitle: '新增分类',
      formData: {
        name: '',
        code: '',
        description: '',
        sort: 0,
        parentId: null
      },
      currentCategory: null,
      isEdit: false
    }
  },
  onLoad() {
    this.fetchCategoryTree();
  },
  methods: {
    // 获取分类树形结构
    fetchCategoryTree() {
      uni.showLoading({
        title: '加载中'
      });
      
      this.$api.get('/api/Category/Tree', { key: this.searchKey })
        .then(res => {
          if (res.data.code === 200) {
            this.treeData = res.data.data.map(item => {
              return {
                ...item,
                expanded: false
              };
            });
          } else {
            this.$u.toast(res.data.msg || '获取分类失败');
          }
        })
        .catch(err => {
          this.$u.toast('网络异常，请稍后重试');
          console.error(err);
        })
        .finally(() => {
          uni.hideLoading();
        });
    },
    
    // 搜索分类
    search() {
      this.fetchCategoryTree();
    },
    
    // 展开/收起子分类
    toggleChildren(item) {
      item.expanded = !item.expanded;
      this.$forceUpdate();
    },
    
    // 打开新增分类弹窗
    openAddDialog() {
      this.isEdit = false;
      this.formTitle = '新增分类';
      this.formData = {
        name: '',
        code: '',
        description: '',
        sort: 0,
        parentId: null
      };
      this.showForm = true;
    },
    
    // 打开添加子分类弹窗
    openAddChildDialog(parent) {
      this.isEdit = false;
      this.formTitle = `添加"${parent.name}"的子分类`;
      this.formData = {
        name: '',
        code: '',
        description: '',
        sort: 0,
        parentId: parent.id
      };
      this.showForm = true;
    },
    
    // 打开编辑分类弹窗
    openEditDialog(category) {
      this.isEdit = true;
      this.currentCategory = category;
      this.formTitle = '编辑分类';
      this.formData = {
        name: category.name,
        code: category.code,
        description: category.description,
        sort: category.sort,
        parentId: category.parentId
      };
      this.showForm = true;
    },
    
    // 确认删除分类
    confirmDelete(category) {
      uni.showModal({
        title: '提示',
        content: `确定要删除"${category.name}"分类吗？`,
        success: res => {
          if (res.confirm) {
            this.deleteCategory(category.id);
          }
        }
      });
    },
    
    // 删除分类
    deleteCategory(categoryId) {
      uni.showLoading({
        title: '删除中'
      });
      
      this.$api.delete(`/api/Category/${categoryId}`)
        .then(res => {
          if (res.data.code === 200) {
            this.$u.toast('删除成功');
            this.fetchCategoryTree();
          } else {
            this.$u.toast(res.data.msg || '删除失败');
          }
        })
        .catch(err => {
          this.$u.toast('网络异常，请稍后重试');
          console.error(err);
        })
        .finally(() => {
          uni.hideLoading();
        });
    },
    
    // 提交表单
    submitForm() {
      this.$refs.uForm.validate(valid => {
        if (valid) {
          if (this.isEdit) {
            this.updateCategory();
          } else {
            this.createCategory();
          }
        }
      });
    },
    
    // 创建分类
    createCategory() {
      uni.showLoading({
        title: '提交中'
      });
      
      this.$api.post('/api/Category', this.formData)
        .then(res => {
          if (res.data.code === 200) {
            this.$u.toast('添加成功');
            this.showForm = false;
            this.fetchCategoryTree();
          } else {
            this.$u.toast(res.data.msg || '添加失败');
          }
        })
        .catch(err => {
          this.$u.toast('网络异常，请稍后重试');
          console.error(err);
        })
        .finally(() => {
          uni.hideLoading();
        });
    },
    
    // 更新分类
    updateCategory() {
      uni.showLoading({
        title: '提交中'
      });
      
      this.$api.put(`/api/Category/${this.currentCategory.id}`, this.formData)
        .then(res => {
          if (res.data.code === 200) {
            this.$u.toast('更新成功');
            this.showForm = false;
            this.fetchCategoryTree();
          } else {
            this.$u.toast(res.data.msg || '更新失败');
          }
        })
        .catch(err => {
          this.$u.toast('网络异常，请稍后重试');
          console.error(err);
        })
        .finally(() => {
          uni.hideLoading();
        });
    }
  }
}
</script>

<style lang="scss">
.content {
  padding: 20rpx;
  
  .toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    
    .u-search {
      flex: 1;
      margin-right: 20rpx;
    }
  }
  
  .tree-container {
    background-color: #ffffff;
    border-radius: 12rpx;
    padding: 20rpx;
    
    .tree-item {
      margin-bottom: 20rpx;
      
      .tree-item-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20rpx;
        background-color: #f8f8f8;
        border-radius: 8rpx;
        
        .tree-item-title {
          display: flex;
          align-items: center;
          
          text {
            margin-left: 10rpx;
            font-size: 32rpx;
            font-weight: bold;
          }
        }
        
        .tree-item-actions {
          display: flex;
          
          .u-button {
            margin-left: 10rpx;
          }
        }
      }
      
      .tree-children {
        margin-left: 40rpx;
        margin-top: 10rpx;
        
        .tree-child-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 20rpx;
          background-color: #f8f8f8;
          border-radius: 8rpx;
          margin-bottom: 10rpx;
          
          .tree-child-title {
            font-size: 28rpx;
          }
        }
      }
    }
  }
  
  .form-container {
    background-color: #ffffff;
    border-radius: 12rpx;
    overflow: hidden;
    
    .form-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx;
      border-bottom: 1px solid #eee;
      
      text {
        font-size: 32rpx;
        font-weight: bold;
      }
    }
    
    .form-content {
      padding: 30rpx;
    }
    
    .form-footer {
      display: flex;
      justify-content: flex-end;
      padding: 20rpx 30rpx 30rpx;
      
      .u-button {
        margin-left: 20rpx;
      }
    }
  }
}
</style> 